package cn.elricyu.tt.config;

import java.net.URL;
import java.util.Collections;
import java.util.List;

import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class RemoteConfig {
	private static final Log logger = LogFactory.getLog(RemoteConfig.class);

	private static XMLConfiguration remoteConf = null;

	static {
		String urlString = Config.getVersionRemoteConfigUrl();
		try {
			URL url = new URL(urlString + "?" + System.currentTimeMillis());
			try {
				remoteConf = new XMLConfiguration(url);
				remoteConf.setAutoSave(false);
				remoteConf.setEncoding("utf-8");
			} catch (Exception e) {
				urlString = Config.getRemoteConfigUrl();
				url = new URL(urlString + "?" + System.currentTimeMillis());
				remoteConf = new XMLConfiguration(url);
				remoteConf.setAutoSave(false);
				remoteConf.setEncoding("utf-8");
			}
		} catch (Exception e1) {
			logger.error(urlString, e1);
		}
	}

	public static int getInt(String key, int defaultValue) {
		try {
			return remoteConf.getInt(key, defaultValue);
		} catch (Exception e) {
		}
		return defaultValue;

	}

	public static String getString(String key, String defaultValue) {
		try {
			return remoteConf.getString(key, defaultValue);
		} catch (Exception e) {
		}
		return defaultValue;
	}

	@SuppressWarnings("unchecked")
	public static List<String> getList(String key) {
		try {
			return remoteConf.getList(key, Collections.EMPTY_LIST);
		} catch (Exception e) {
		}
		return Collections.EMPTY_LIST;
	}

	public static boolean getBoolean(String key, boolean defaultValue) {
		try {
			String v = remoteConf.getString(key);
			if (StringUtils.isBlank(v)) {
				return defaultValue;
			}
			return ("true".equalsIgnoreCase(v) || "1".equals(v));
		} catch (Exception e) {
		}
		return defaultValue;
	}
}
